<template>
  <div class="js-transition-demo">
    <h2>JavaScript 钩子过渡</h2>

    <button @click="show = !show">切换显示</button>

    <Transition
      @before-enter="onBeforeEnter"
      @enter="onEnter"
      @after-enter="onAfterEnter"
      @before-leave="onBeforeLeave"
      @leave="onLeave"
      @after-leave="onAfterLeave"
      :css="false"
    >
      <div v-if="show" class="js-box">使用 JavaScript 控制的动画</div>
    </Transition>
  </div>
</template>
<script setup>
import { ref } from 'vue'

const show = ref(false)

// JavaScript 钩子函数
const onBeforeEnter = (el) => {
  el.style.opacity = 0
  el.style.transform = 'scale(0) rotate(180deg)'
}

const onEnter = (el, done) => {
  el.style.transition = 'all 0.5s ease'

  // 使用 requestAnimationFrame 确保动画流畅
  requestAnimationFrame(() => {
    el.style.opacity = 1
    el.style.transform = 'scale(1) rotate(0deg)'
  })

  // 监听过渡结束事件
  el.addEventListener('transitionend', done)
}

const onAfterEnter = (el) => {
  console.log('进入动画完成')
}

const onBeforeLeave = (el) => {
  console.log('准备离开')
}

const onLeave = (el, done) => {
  el.style.transition = 'all 0.3s ease'
  el.style.opacity = 0
  el.style.transform = 'scale(0) rotate(-180deg)'

  el.addEventListener('transitionend', done)
}

const onAfterLeave = (el) => {
  console.log('离开动画完成')
}
</script>
<style scoped>
.js-transition-demo {
  padding: 20px;
  text-align: center;
}

.js-box {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 10px;
  margin: 20px auto;
  max-width: 300px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

button {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}
</style>
